/**
 * 
 */
package main.org.form.action;

import java.math.BigDecimal;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.org.model.Utils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.compiere.dsr.DSR_Cell;
import org.compiere.dsr.DSR_DataCollection;
import org.compiere.model.I_BPM_FormValues;
import org.compiere.model.MBPMForm;
import org.compiere.model.MBPMFormValues;
import org.compiere.model.MBPMSubs;
import org.compiere.model.X_BPM_FormCode;
import org.compiere.model.X_C_Project;
import org.compiere.util.DB;
import org.compiere.util.Env;

/**
 * @author V.Sokolov
 *
 */
public class FormBP extends Forms implements ServletRequestAware,ServletResponseAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7222019810593858920L;
	/* */
	public static final String sessionKey = "formBP";
	DSR_DataCollection collection;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private int projectID;
	private int ProjectSubID;
	private int userID;
	LinkedHashMap<Integer, String> projectList = new LinkedHashMap<Integer, String>();
	
	public DSR_DataCollection getCollection() {
		return collection;
	}
	public void setCollection(DSR_DataCollection collection) {
		this.collection = collection;
	}
	
	public void setServletRequest(HttpServletRequest request){
		this.request = request;
	}
	public HttpServletRequest request(){
		return request;
	}

	public void setServletResponse(HttpServletResponse response){
		this.response = response;
	}
	public HttpServletResponse getServletResponse(){
		return response;
	}

	public int getProjectID() {
		return projectID;
	}
	public void setProjectID(int projectID) {
		this.projectID = projectID;
	}

	public int getProjectSubID() {
		return ProjectSubID;
	}
	public void setProjectSubID(int projectSubID) {
		ProjectSubID = projectSubID;
	}
	
	public int getUserID() {
		return userID;
	}
	public void setUserID(int userID) {
		this.userID = userID;
	}

	public LinkedHashMap<Integer, String> getProjectList() {
		return projectList;
	}
	public void setProjectList() {
		loadProjects();
	}
	
	/* 
	 */
	@Override
	public String execute() throws Exception {
		
		StringBuilder err = new StringBuilder();
		if(getSubsID() == MBPMSubs.getHeadSubsID())
			err.append("Для головной компании формы ввода не предусмотрены <br />");
		
		setMessageError(err.toString());
		if(err.length() != 0)
			return NONE;
		
		Forms fo = (Forms) session.get(Forms.sessionKey);
		fo.setPage(Utils.TEMPLATE_SECOND);
		session.put(Forms.sessionKey, fo);
		setPage(Utils.TEMPLATE_SECOND);
		super.setBudget();
		DSR_DataCollection collection = new DSR_DataCollection(getFormID(), getProjectID(), getSubsID(), getProjectSubID());
		setCollection(collection);
		session.put(FormBP.sessionKey, this);

		MBPMForm form = new MBPMForm(Env.getCtx(), getFormID(), null);
		if(form.getBPM_FormCode().getCategoryName().equals(X_BPM_FormCode.CATEGORYNAME_Profitability)
				&& getProjectSubID() == 0){
			
			setProjectList();
			if(getProjectList().size() == 0)
				err.append("Не найден проект для ДЗО <br />");
			
			setMessageError(err.toString());
			if(err.length() != 0)
				return NONE;
			
			return X_BPM_FormCode.CATEGORYNAME_Profitability;
		}
		
		return SUCCESS;
	}
	
	/*
	 */
	@Override
	public String input() throws Exception {
		
		StringBuilder err = new StringBuilder();
		
		FormBP foBP = (FormBP) session.get(FormBP.sessionKey);
		setCollection(foBP.getCollection());
		
		if(getSubsID() == MBPMSubs.getHeadSubsID())
			err.append("Для головной компании формы ввода не предусмотрены <br />");
		
		setMessageError(err.toString());
		if(err.length() != 0)
			return NONE;
		
		int counts = 0;
		if(getProjectSubID() != 0)
			counts = MBPMFormValues.countValues(projectID, getFormID(), getSubsID(), getProjectSubID());
		else
			counts = MBPMFormValues.countValues(projectID, getFormID(), getSubsID());
		
		if(counts != 0){
			updateValues(foBP);
		}else{
			insertValues(foBP);
		}		
		
		return INPUT;
	}
	
	private boolean updateValues(FormBP fb){
		
		String upd = "update "+I_BPM_FormValues.Table_Name;
		String set = "";
		String where = " where BPM_Project_ID="+getProjectID()
				+"\n and BPM_Subs_ID="+getSubsID()
				+"\n and BPM_Form_ID="+getFormID();
		if(getProjectSubID() != 0)
			where += "\n and BPM_SubsProject_ID="+getProjectSubID();
		String periodSql = "";
		
		DSR_Cell cell = null;
		String value = "";
		int row = 1;
		int col = 0;
		for(int i=0; i < collection.size(); i++){
			col = 0;
			for(int j=0; j < collection.getRow(i).size(); j++){
				cell = collection.getRow(i).getCell(j);
				if(!cell.isRow)
					value = request.getParameter("cell_Row"+row+"_Col"+col);
				
				periodSql = "\n and BPM_FormLine_ID="+cell.getBPM_FormLine_ID()
						+"\n and BPM_FormColumn_ID="+cell.getBPM_FormColumn_ID();
				set = " set cellValue='"+value+"'";
				
				DB.executeUpdate(upd+set+where+periodSql, null);
				periodSql = "";
				set = "";
				col++;
			}
			row++;
		}
		return true;
	}
	
	private int insertValues(FormBP fb){
		
		DSR_Cell cell = null;
		MBPMFormValues formValues = null;
		String value = "";
		int count = 1;
		int row = 1;
		int col = 0;
		for(int i=0; i < collection.size(); i++){
			col = 0;
			for(int j=0; j < collection.getRow(i).size(); j++){
				cell = collection.getRow(i).getCell(j);
				if(!cell.isRow){
					value = request.getParameter("cell_Row"+row+"_Col"+col);
					formValues = new MBPMFormValues(Env.getCtx(), 0, null);
					formValues.setBPM_Form_ID(getFormID());
					formValues.setBPM_FormCell_ID(cell.getBPM_FormCell_ID());
					formValues.setBPM_FormLine_ID(cell.getBPM_FormLine_ID());
					formValues.setBPM_FormColumn_ID(cell.getBPM_FormColumn_ID());
					formValues.setBPM_VersionBudget_ID(fb.getBudget().getBPM_VersionBudget_ID());
					formValues.setBPM_Project_ID(getProjectID());
					if(getProjectSubID() != 0)
						formValues.setBPM_SubsProject_ID(getProjectSubID());
					formValues.setBPM_Subs_ID(getSubsID());
					formValues.setCellValue(value);
					formValues.setAlternateValue("");
					formValues.saveEx();
				}
				col++;
			}
			count++;
			row++;
		}
		return count;
	}		
	
	public static String getNBSP(int count){
		
		String nbsp = "";
		int i = 0;
		while(i < count){
			nbsp += "&nbsp;&nbsp;&nbsp;";
			i++;
		}
		return nbsp;
	}
	
	private void loadProjects(){
		
		X_C_Project[] project = MBPMSubs.getLinesProject(Env.getCtx(), getSubsID(), null);
		if(project.length > 0)
			setDefaultProjectID(project[0].getC_Project_ID());
		for(X_C_Project p: project){
			this.projectList.put(p.getC_Project_ID(), p.getName());
		}
		
	}

}
